package com.example.itshome.network;

import android.app.Activity;
import android.util.Log;
import com.example.itshome.entity.UserEntity;
import com.example.itshome.manager.UserInfoManager;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;
import java.util.Set;

public class InitUserInfoRequest extends AbstractNetworkRequest{
    private UserEntity entity;


    public InitUserInfoRequest setEntity(UserEntity entity) {
        this.entity = entity;
        return this;
    }

    public InitUserInfoRequest(Activity activity) {
        super(activity);
    }

    @Override
    protected String getPathAndParams() {
        //Log.i("",UserInfoManager.getInstance().getUser().getUsername());
        return "user/init?username="+ UserInfoManager.getInstance().getUser().getUsername();
    }

    @Override
    protected void handleResult(String result) {
        //Log.i("initRequest",UserInfoManager.getInstance().getTokenRequest());
        try {
            JSONObject resultJson= new JSONObject(result);
            int code = resultJson.getInt("code");
            if(code!=200){
                return;
            }

            resultJson=resultJson.getJSONObject("data");
            entity.setHeaderSrc(DOMAIN_HOST+"images"+resultJson.getString("head_sculpture_path"))
                    .setUsername(resultJson.getString("username"))
                    .setNickname(resultJson.getString("nickname"))
                    .setIntroduction(resultJson.getString("introduction"))
                    .setIntegral(jsonGetInt(resultJson,"integral"))
                    .setCollectionCount(jsonGetInt(resultJson,"favoriteCount"))
                    .setPostCount(jsonGetInt(resultJson,"momentsCount"))
                    .setClockInCount(resultJson.getInt("signInCount"));
            setHandleResultRunnable(new Runnable() {
                @Override
                public void run() {
                    UserInfoManager.getInstance().callRunner();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private int jsonGetInt(JSONObject jsonObject,String s)throws JSONException{
        if(jsonObject.isNull(s)){
            return 0;
        }else {
            return jsonObject.getInt(s);
        }

    }

    @Override
    protected void handleException(Exception exception) {
        setHandleExceptionRunnable(new Runnable() {
            @Override
            public void run() {
                exception.printStackTrace();
                entity.setHeaderSrc("")
                        .setUsername("xiao_cheng")
                        .setNickname("小橙")
                        .setIntroduction("我是一个保安，保卫一方平安");
                UserInfoManager.getInstance().callRunner();
            }
        });
    }
}
